package com.synjones.bluetoothInterface;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SimpleExpandableListAdapter;

import com.synjones.bluetoothreadersdk.R;

public class GetBtDevicesListView {
	Set<BluetoothDevice> pairedDevices;
	Context mContext;
	android.app.AlertDialog ad;
	OnClickListener discovery;
	SimpleExpandableListAdapter sela ;
	Handler handler;
	ExpandableListView elv;
	List<Map<String, String>> childs_unpaired = new LinkedList<Map<String,String>>();
	
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
	   public void onReceive(Context context, Intent intent) {
	        String action = intent.getAction();
	        // When discovery finds a device
	        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
	            // Get the BluetoothDevice object from the Intent
	            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
	            // Add the name and address to an array adapter to show in a ListView
	            String mac=device.getAddress();
	        	Map<String, String> content = new HashMap<String, String>();
	            for(Map<String, String> map:childs_unpaired){
	            	String tmpName=map.get("childName");
	            	if(mac.equals(map.get("childMac"))) {
	            		if(tmpName!=null && !tmpName.isEmpty()) return;
	            		childs_unpaired.remove(map);
	            		break;//如果该mac已经在列表中，则不添加该mac
	            	}
	            }
				content.put("childName", device.getName());
				content.put("childMac", mac);
	            childs_unpaired.add(content);

	            sela.notifyDataSetChanged();
	        }
	    }
	};
	
	
	public GetBtDevicesListView(Context mContext,Set<BluetoothDevice> pairedDevices,OnClickListener discovery,Handler handler){
		this.pairedDevices=pairedDevices;
		this.mContext=mContext;
		setOkClick(discovery);
		this.handler=handler;
		getView();
		// Register the BroadcastReceiver
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		mContext.registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
		
	}
	public void setOkClick(OnClickListener discovery){
		this.discovery=discovery;
	}
	
	class ClickWrap implements View.OnClickListener{
		private View.OnClickListener listener;
		public ClickWrap( View.OnClickListener listener){
			this.listener=listener;
		}
		@Override
		public void onClick(View arg0) {
			if(listener!=null)
				listener.onClick(arg0);
		}			
	} 
	
	class Click extends ClickWrap{
		public Click(OnClickListener listener) {
			super(listener);
		}
		@Override
		public void onClick(View arg0) {
			elv.collapseGroup(0);
			elv.collapseGroup(1);
			super.onClick(arg0);
		}
	}
	
	public void disMiss(){
		try {
			mContext.unregisterReceiver(mReceiver);
			ad.dismiss();
		} catch (Exception e) {
		}
	}
	
	public void getView(){
		ad=new AlertDialog.Builder(mContext).create();
		ad.show();
		ad.setCancelable(false);
		Window window = ad.getWindow();
		window.setContentView(R.layout.show_bt_devices);
		elv=(ExpandableListView)window.findViewById(R.id.elvBtDevice);
		Button btn=(Button)window.findViewById(R.id.elvBtnCancel);
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				handler.obtainMessage(BluetoothReader.CANCEL_SELECT_DEVICE).sendToTarget();
				disMiss();
			}
		});
		btn=(Button)window.findViewById(R.id.elvBtnDiscovery);
		btn.setOnClickListener(new Click(discovery));
		
		 //创建二个一级条目标题
        Map<String, String> title_0 = new HashMap<String, String>();
        Map<String, String> title_1 = new HashMap<String, String>();
        Map<String, String> title_2 = new HashMap<String, String>();
        title_0.put("group", "最近连接的设备");
        title_1.put("group", "已配对");
        title_2.put("group", "搜索结果");
       
        //创建一级条目容器
        List<Map<String, String>> groups = new ArrayList<Map<String,String>>();
        groups.add(title_0);
        groups.add(title_1);
        groups.add(title_2);
       
        //创建二级条目内容
       
        //内容一
        
        List<Map<String, String>> childs_paired = new ArrayList<Map<String,String>>();
        
		for (BluetoothDevice device : pairedDevices) {
			Map<String, String> content = new HashMap<String, String>();
			content.put("childName", device.getName());
			content.put("childMac", device.getAddress());
			childs_paired.add(content);
		}
       
        //内容二
		
       
        //存放两个内容, 以便显示在列表中
        List<List<Map<String, String>>> childs = new ArrayList<List<Map<String,String>>>();

        
        childs.add(getLastDevice());
        childs.add(childs_paired);
        childs.add(childs_unpaired);
       
        //创建ExpandableList的Adapter容器
        //参数: 1.上下文    2.一级集合    3.一级样式文件 4. 一级条目键值        5.一级显示控件名
        //         6. 二级集合    7. 二级样式    8.二级条目键值    9.二级显示控件名
        
        sela  = new SimpleExpandableListAdapter(
                mContext, groups, R.drawable.groups,new String[]{"group"}, new int[]{R.id.textGroup},
                childs, R.drawable.childs, new String[]{"childName","childMac"}, new int[]{R.id.tvChildName,R.id.tvChildMac});
        
        elv.setAdapter(sela);
        elv.expandGroup(0);
        elv.expandGroup(1);
        elv.expandGroup(2);
        elv.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
                    int groupPosition, int childPosition, long id) {
				HashMap<String, String> map=(HashMap<String, String>) sela.getChild(groupPosition, childPosition);
				String mac=map.get("childMac");
				handler.obtainMessage(BluetoothReader.CONNECT_BT_DEVICE, mac).sendToTarget();
				disMiss();
				return false;
			}
		});
        
	}
	
	public void addToList(HashMap<String, String> map){
		
	}
	
	private  List<Map<String, String>> getLastDevice(){
		List<Map<String, String>> deviceList=new ArrayList<Map<String,String>>();
        SharedPreferences sp=mContext.getSharedPreferences("btconfig", Context.MODE_PRIVATE);
        String devName = sp.getString("syn_dev_Name", "");
        String devMAC = sp.getString("syn_dev_Mac", "");
        if(!devName.isEmpty() && !devMAC.isEmpty()){
        	Map<String, String> content = new HashMap<String, String>();
    		content.put("childName", devName);
    		content.put("childMac", devMAC);
    		deviceList.add(content);
        }
        return deviceList;
	}
	
}
